package com.qlyl.modules.information.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qlyl.common.api.vo.Result;
import com.qlyl.common.constant.CommonConstant;
import com.qlyl.common.system.api.ISysBaseAPI;
import com.qlyl.common.system.base.controller.JeecgController;
import com.qlyl.common.system.query.QueryGenerator;
import com.qlyl.common.system.util.JwtUtil;
import com.qlyl.common.util.PasswordUtil;
import com.qlyl.common.util.RedisUtil;
import com.qlyl.common.util.oConvertUtils;
import com.qlyl.modules.information.entity.AppUser;
import com.qlyl.modules.information.entity.Consumers;
import com.qlyl.modules.information.entity.EthWallet;
import com.qlyl.modules.information.service.IAppUserService;
import com.qlyl.modules.information.service.IConsumersService;
import com.qlyl.modules.information.service.IEthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@RequestMapping("/appuser")
@RestController
public class AppUserController extends JeecgController<AppUser, IAppUserService> {

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private IEthService iEthService;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IConsumersService consumersService;

    /**
     * 生成在添加用户情况下没有主键的问题,返回给前端
     *
     * @return
     */
    @RequestMapping(value = "/generateUserId", method = RequestMethod.GET)
    public Result<String> generateUserId() {
        Result<String> result = new Result<>();
        System.out.println("我执行了,生成用户ID==============================");
        String userId = UUID.randomUUID().toString().replace("-", "");
        result.setSuccess(true);
        result.setResult(userId);
        return result;
    }

    /**
     * 列表
     *
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<AppUser>> queryPageList(AppUser appUser, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<AppUser>> result = new Result<IPage<AppUser>>();
        QueryWrapper<AppUser> queryWrapper = QueryGenerator.initQueryWrapper(appUser, req.getParameterMap());
        Page<AppUser> page = new Page<AppUser>(pageNo, pageSize);
        IPage<AppUser> pageList = appUserService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 添加
     *
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
/*
    @RequiresPermissions("appUser:add")
*/
    public Result<AppUser> add(@RequestBody JSONObject jsonObject) {
        Result<AppUser> result = new Result<AppUser>();
        try {
            AppUser appUser = JSON.parseObject(jsonObject.toJSONString(), AppUser.class);
            appUser.setCreateTime(new Date());//设置创建时间
            String salt = oConvertUtils.randomGen(8);
            appUser.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(appUser.getUsername(), appUser.getPassword(), salt);
            appUser.setPassword(passwordEncode);
            appUser.setUserStatus(1);
            appUser.setBindingStatus(-1);
            appUser.setAccountBalance(new BigDecimal(0.0000));
            appUser.setDelFlag(0);
            //生成区块链钱包
            EthWallet ethWallet = appUserService.createWallet();
            appUser.setWalletId(ethWallet.getId());
            appUserService.save(appUser);
            // 给刚创建的钱包转一笔ether
            iEthService.rechargeEthWalletByAsyncAndFree(ethWallet.getAddress());
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑修改
     *
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
//    @RequiresPermissions("appUser:edit")
    public Result<AppUser> edit(@RequestBody JSONObject jsonObject) {
        Result<AppUser> result = new Result<AppUser>();
        try {
            AppUser appUser = appUserService.getById(jsonObject.getString("id"));
            sysBaseAPI.addLog("编辑用户信息，id： " + jsonObject.getString("id"), CommonConstant.LOG_TYPE_2, 2);
            if (appUser == null) {
                result.error500("未找到对应实体");
            } else {
                AppUser editAppUser = JSON.parseObject(jsonObject.toJSONString(), AppUser.class);
                //String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), sysUser.getSalt());
                editAppUser.setPassword(appUser.getPassword());
                appUserService.updateById(editAppUser);
                result.success("修改成功!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 删除用户
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        sysBaseAPI.addLog("删除企业信息，id： " + id, CommonConstant.LOG_TYPE_2, 3);
        this.appUserService.removeById(id);
        return Result.ok("删除成功");
    }

    /**
     * 批量删除用户
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        sysBaseAPI.addLog("批量删除用户信息， ids： " + ids, CommonConstant.LOG_TYPE_2, 3);
        this.appUserService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除企业成功");
    }

    /**
     * 冻结&解冻用户
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/frozenBatch", method = RequestMethod.PUT)
    public Result<AppUser> frozenBatch(@RequestBody JSONObject jsonObject) {
        Result<AppUser> result = new Result<AppUser>();
        try {
            String ids = jsonObject.getString("ids");
            String status = jsonObject.getString("userStatus");
            String[] arr = ids.split(",");
            for (String id : arr) {
                if (oConvertUtils.isNotEmpty(id)) {
                    this.appUserService.update(new AppUser().setUserStatus(Integer.valueOf(status)),
                            new UpdateWrapper<AppUser>().lambda().eq(AppUser::getId, id));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败" + e.getMessage());
        }
        result.success("操作成功!");
        return result;

    }

    /**
     * 审核录入企业信息（绑定审核）
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/frozenBatchChcek", method = RequestMethod.PUT)
    public Result<AppUser> frozenBatchChcek(@RequestBody JSONObject jsonObject) {
        Result<AppUser> result = new Result<AppUser>();
        String ids = jsonObject.getString("ids");
        String bindingStatus = jsonObject.getString("bindingStatus");
        boolean flag = appUserService.frozenBatchChcek(ids,bindingStatus);
        if(flag){
            result.success("操作成功!");
        }else{
            result.error500("操作失败");
        }
        return result;

    }


    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result<AppUser> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<AppUser> result = new Result<AppUser>();
        AppUser  appUser = appUserService.getById(id);
        if (appUser == null) {
            result.error500("未找到对应实体");
        } else {
            //加公司名称（不想写关联查询）
            Consumers consumers = consumersService.getById(appUser.getConsumersId());
            if(consumers!=null){
                appUser.setCompanyName(consumers.getCompanyName());
            }
            result.setResult(appUser);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 校验用户账号是否唯一<br>
     * 可以校验其他 需要检验什么就传什么。。。
     *
     * @param appUser
     * @return
     */
    @RequestMapping(value = "/checkOnlyAppUser", method = RequestMethod.GET)
    public Result<Boolean> checkOnlyAppUser(AppUser appUser) {
        Result<Boolean> result = new Result<>();
        //如果此参数为false则程序发生异常
        result.setResult(true);
        try {
            //通过传入信息查询新的用户信息
            AppUser newAppUser = appUserService.getOne(new QueryWrapper<AppUser>(appUser));
            if (newAppUser != null) {
                result.setSuccess(false);
                result.setMessage("用户账号已存在");
                return result;
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            return result;
        }
        result.setSuccess(true);
        return result;
    }

    /**
     * 修改密码
     */
    @RequestMapping(value = "/changPassword", method = RequestMethod.PUT)
    public Result<?> changPassword(@RequestBody AppUser appUser) {
        AppUser user = this.appUserService.getOne(new LambdaQueryWrapper<AppUser>().eq(AppUser::getUsername, appUser.getUsername()));
        if (user == null) {
            return Result.error("用户不存在！");
        }
        appUser.setId(user.getId());
        return appUserService.changePassword(appUser);
    }


    /**
     * 导出excel
     * @param appUser
     * @param request
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(AppUser appUser, HttpServletRequest request) {

        return exportXls(request,appUser,AppUser.class,"APP用户信息列表");

    }


    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("appUser:import")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return importExcel(request,response,AppUser.class);
    }


    /**
     * @param appUserIds
     * @return
     * @功能：根据id 批量查询
     */
    @RequestMapping(value = "/queryByIds", method = RequestMethod.GET)
    public Result<Collection<AppUser>> queryByIds(@RequestParam String appUserIds) {
        Result<Collection<AppUser>> result = new Result<>();
        String[] appUserId = appUserIds.split(",");
        Collection<String> idList = Arrays.asList(appUserId);
        Collection<AppUser> appUserList = appUserService.listByIds(idList);
        result.setSuccess(true);
        result.setResult(appUserList);
        return result;
    }

    /**
     * 重置密码
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.PUT)
    public Result<?> changPassword(@RequestBody JSONObject json) {
        String username = json.getString("username");
        String oldpassword = json.getString("oldpassword");
        String password = json.getString("password");
        String confirmpassword = json.getString("confirmpassword");
        AppUser user = this.appUserService.getOne(new LambdaQueryWrapper<AppUser>().eq(AppUser::getUsername, username));
        if (user == null) {
            return Result.error("用户不存在！");
        }
        return appUserService.resetPassword(username, oldpassword, password, confirmpassword);
    }

    /**
     * 根据用户名和手机号查基本信息
     * @param
     * @return
     */
    @GetMapping("/queryAppUser")
    public Result<Map<String, Object>> queryAppUser(AppUser appUser) {
        String cphone = appUser.getCphone();
        String username = appUser.getUsername();
        Result<Map<String, Object>> result = new Result<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        if (oConvertUtils.isNotEmpty(cphone)) {
            AppUser selAppUser = appUserService.getAppUserByPhone(cphone);
            if (selAppUser != null) {
                map.put("username", selAppUser.getUsername());
                map.put("cphone", selAppUser.getCphone());
                result.setSuccess(true);
                result.setResult(map);
                return result;
            }
        }
        if (oConvertUtils.isNotEmpty(username)) {
            AppUser selAppUser = appUserService.getAppUserByName(username);
            if (selAppUser != null) {
                map.put("username", selAppUser.getUsername());
                map.put("cphone", selAppUser.getCphone());
                result.setSuccess(true);
                result.setResult(map);
                return result;
            }
        }
        result.setSuccess(false);
        result.setMessage("验证失败");
        return result;
    }

    /**
     * 根据TOKEN获取用户的部分信息（返回的数据是可供表单设计器使用的数据）
     *
     * @return
     */
    @GetMapping("/getUserSectionInfoByToken")
    public Result<?> getUserSectionInfoByToken(HttpServletRequest request, @RequestParam(name = "token", required = false) String token) {
        try {
            String username = null;
            // 如果没有传递token，就从header中获取token并获取用户信息
            if (oConvertUtils.isEmpty(token)) {
                username = JwtUtil.getUserNameByToken(request);
            } else {
                username = JwtUtil.getUsername(token);
            }

            log.info(" ------ 通过令牌获取部分用户信息，当前用户： " + username);

            // 根据用户名查询用户信息
            AppUser appUser = appUserService.getAppUserByName(username);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("appUserId", appUser.getId());
            map.put("appUsername", appUser.getUsername()); // 当前登录用户登录账号

            log.info(" ------ 通过令牌获取部分用户信息，已获取的用户信息： " + map);

            return Result.ok(map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(500, "查询失败:" + e.getMessage());
        }
    }


    /**
     * 用户手机号验证
     */
    @PostMapping("/cphoneVerification")
    public Result<String> cphoneVerification(@RequestBody JSONObject jsonObject) {
        Result<String> result = new Result<String>();
        String cphone = jsonObject.getString("cphone");
        String smscode = jsonObject.getString("smscode");
        Object code = redisUtil.get(cphone);
        if (!smscode.equals(code)) {
            result.setMessage("手机验证码错误");
            result.setSuccess(false);
            return result;
        }
        redisUtil.set(cphone, smscode);
        result.setResult(smscode);
        result.setSuccess(true);
        return result;
    }

    /**
     * 用户重置更改密码
     */
    @PostMapping("/passwordChange")
    public Result<AppUser> passwordChange(@RequestBody JSONObject jsonObject) {
        Result<AppUser> result = new Result<AppUser>();
        String cphone   = jsonObject.getString("cphone");
        String smscode  = jsonObject.getString("smscode");
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");
        AppUser appUser = new AppUser();
        Object object = redisUtil.get(cphone);
        if (null == object) {
            result.setMessage("更改密码失败");
            result.setSuccess(false);
        }
        if (!smscode.equals(object)) {
            result.setMessage("更改密码失败");
            result.setSuccess(false);
        }
        appUser = this.appUserService.getOne(new LambdaQueryWrapper<AppUser>().eq(AppUser::getUsername, username));
        if (appUser == null) {
            result.setMessage("未找到对应实体");
            result.setSuccess(false);
            return result;
        } else {
            String salt = oConvertUtils.randomGen(8);
            appUser.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(appUser.getUsername(), password, salt);
            appUser.setPassword(passwordEncode);
            this.appUserService.updateById(appUser);
            result.setSuccess(true);
            result.setMessage("密码修改完成！");
            return result;
        }
    }



//    /**
//     * 手机号登录接口
//     *
//     * @param jsonObject
//     * @return
//     */
//    @ApiOperation("手机号登录接口")
//    @PostMapping("/phoneLogin")
//    public Result<JSONObject> phoneLogin(@RequestBody JSONObject jsonObject) {
//        Result<JSONObject> result = new Result<JSONObject>();
//        String phone = jsonObject.getString("mobile");
//
//        //校验用户有效性
//        SysUser sysUser = sysUserService.getUserByPhone(phone);
//        result = sysUserService.checkUserIsEffective(sysUser);
//        if (!result.isSuccess()) {
//            return result;
//        }
//
//        String smscode = jsonObject.getString("captcha");
//        Object code = redisUtil.get(phone);
//        if (!smscode.equals(code)) {
//            result.setMessage("手机验证码错误");
//            return result;
//        }
//        //用户信息
//        userInfo(sysUser, result);
//        //添加日志
//        sysBaseAPI.addLog("用户名: " + sysUser.getUsername() + ",登录成功！", CommonConstant.LOG_TYPE_1, null);
//
//        return result;
//    }



}
